package ru.dc.gui.swing;

import org.apache.commons.lang.StringUtils;
import org.jdesktop.swingx.JXTable;
import ru.dc.Application;
import ru.dc.gui.swing.util.FileInfoRenderer;
import ru.dc.gui.swing.util.SizeRenderer;
import ru.dc.object.DownloadItem;
import ru.dc.object.DownloadSource;
import ru.dc.object.FileInfo;
import ru.dc.util.FilelistUtils;

import javax.swing.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.Collections;

/**
 * Панель для отображения списка файлов пользователя.
 */
public class FilesList extends Tab {
    private JPanel rootPanel;
    private JTree directories;
    private JXTable files;
    private FileInfo fileList;
    private DownloadSource source;

    public FilesList() {
        addPropertyChangeListener("fileList", new PropertyChangeListener() {
            public void propertyChange(PropertyChangeEvent evt) {
                loadFiles((FileInfo) evt.getNewValue());
            }
        });

        directories.addTreeSelectionListener(new TreeSelectionListener() {
            public void valueChanged(TreeSelectionEvent e) {
                if (e.getNewLeadSelectionPath()==null) {
                    showFiles(null);
                    return;
                }
                DefaultMutableTreeNode selected = (DefaultMutableTreeNode) e.getNewLeadSelectionPath().getLastPathComponent();
                FileInfo file = (FileInfo) selected.getUserObject();
                showFiles(file);
            }
        });

        files.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount()==2 && SwingUtilities.isLeftMouseButton(e)) {
                    int viewRow = files.rowAtPoint(e.getPoint());
                    int modelRow = files.convertRowIndexToModel(viewRow);
                    DefaultTableModel model = (DefaultTableModel) files.getModel();
                    FileInfo file = (FileInfo) model.getValueAt(modelRow, 0);

                    DownloadItem item = new DownloadItem();
                    item.setFilename(FilelistUtils.generatePathFromRoot(file));
                    item.setLength(file.getLength());
                    item.setTth(file.getTth());
                    item.getSource().setNick(source.getNick());
                    item.getSource().setHub(source.getHub());
                    Application.getApplication().getDownloadQueue().enqueueItem(item);
                }
            }
        });

    }

    private void showFiles(FileInfo fileInfo) {
        DefaultTableModel model = new DefaultTableModel();
        model.addColumn("Файл");
        model.addColumn("Размер");
        if (fileInfo!=null) {
            for (FileInfo file : fileInfo.getChildren()) {
                model.addRow(new Object[] {file, file.getLength()});
            }
        }
        files.setModel(model);
        files.getColumnModel().getColumn(0).setCellRenderer(new FileInfoRenderer());
        files.getColumnModel().getColumn(1).setCellRenderer(new SizeRenderer());
    }

    private void loadFiles(FileInfo fileInfo) {
        DefaultMutableTreeNode root = createTreeNode(fileInfo);
        DefaultTreeModel model = new DefaultTreeModel(root);
        directories.setModel(model);
    }

    private DefaultMutableTreeNode createTreeNode(FileInfo fileInfo) {
        DefaultMutableTreeNode node = new DefaultMutableTreeNode(fileInfo);
        node.setAllowsChildren(true);
        for (FileInfo child : fileInfo.getChildren()) {
            if (child.isDirectory()) {
                node.add(createTreeNode(child));
            }
        }
        return node;
    }

    @Override
    public void init() {
        super.init();

        showFiles(null);
        setLayout(new BorderLayout());
        add(rootPanel);
    }

    public FileInfo getFileList() {
        return fileList;
    }

    public void setFileList(FileInfo fileList) {
        FileInfo old = this.fileList;
        this.fileList = fileList;
        firePropertyChange("fileList", old, fileList);
    }

    public void setSource(DownloadSource source) {
        this.source = source;
    }

    @Override
    public void close() {
        super.close();
        FilelistUtils.removeUsersFilelist(source);
    }
}
